# alert_manager.py
import json
import logging
from datetime import datetime, timedelta
from typing import Dict, Set
from config import ALERT_RECORD_FILE

logger = logging.getLogger(__name__)

class AlertManager:
    """报警记录管理器"""
    
    def __init__(self, record_file: str = ALERT_RECORD_FILE):
        self.record_file = record_file
        self.alert_records: Dict[str, str] = self._load_records()
    
    def _load_records(self) -> Dict[str, str]:
        """加载报警记录"""
        try:
            with open(self.record_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return {}
    
    def _save_records(self):
        """保存报警记录"""
        try:
            with open(self.record_file, 'w', encoding='utf-8') as f:
                json.dump(self.alert_records, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存报警记录失败: {e}")
    
    def should_alert(self, symbol: str, change_percent: float) -> bool:
        """
        检查是否应该发送报警
        
        Args:
            symbol: 股票代码
            change_percent: 涨跌幅
            
        Returns:
            bool: 是否应该发送报警
        """
        current_time = datetime.now().isoformat()
        
        # 检查是否已经报警过（防止重复报警）
        if symbol in self.alert_records:
            last_alert_time = datetime.fromisoformat(self.alert_records[symbol])
            # 如果上次报警在1小时内，不再重复报警
            if datetime.now() - last_alert_time < timedelta(hours=1):
                return False
        
        # 更新报警记录
        self.alert_records[symbol] = current_time
        self._save_records()
        return True
    
    def cleanup_old_records(self, hours: int = 24):
        """清理旧的报警记录"""
        cutoff_time = datetime.now() - timedelta(hours=hours)
        updated = False
        
        for symbol, alert_time_str in list(self.alert_records.items()):
            alert_time = datetime.fromisoformat(alert_time_str)
            if alert_time < cutoff_time:
                del self.alert_records[symbol]
                updated = True
        
        if updated:
            self._save_records()
            logger.info("已清理旧的报警记录")